﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml;
using MediaPortal.Configuration;
using System.Net;

namespace MyEmulators2
{
    class ImageHandler
    {
        public ImageHandler() 
        {
            aspects = loadAspects();
        }

        Dictionary<string, double> aspects;

        #region Singleton

        static ImageHandler instance = null;

        public static ImageHandler Instance
        {
            get 
            {
                if (instance == null)
                    instance = new ImageHandler();
                return instance;
            }
        }

        #endregion

        public Image NewImage(Image input)
        {
            if (input == null)
                return null;

            Image output = new Bitmap(input.Width, input.Height, PixelFormat.Format32bppPArgb);

            using (Graphics graphics = Graphics.FromImage(output))
                graphics.DrawImage(input, 0, 0, input.Width, input.Height);

            return output;
        }

        public Image resizeImage(Image input, double ratio)
        {
            if (input == null)
                return null;

            if (ratio <= 0 || !Options.Instance.GetBoolOption("resizethumbs"))
                return NewImage(input);

            int newWidth;
            int newHeight;
            if (input.Width > input.Height)
            {
                newWidth = input.Width;
                newHeight = Convert.ToInt32(input.Width / ratio);
            }
            else
            {
                newWidth = Convert.ToInt32(input.Height * ratio);
                newHeight = input.Height;
            }

            Image output = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppPArgb);
            using (Graphics graphics = Graphics.FromImage(output))
            {
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.DrawImage(input, 0, 0, newWidth, newHeight);
            }
            return output;
        }

        public Bitmap BitmapFromWeb(string URL)
        {
            try
            {
                // create a web request to the url of the image
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
                // set the method to GET to get the image
                myRequest.Method = "GET";
                myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:6.0.1) Gecko/20100101 Firefox/6.0.1";
                // get the response from the webpage
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                // create a bitmap from the stream of the response
                Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
                // close off the stream and the response
                myResponse.Close();
                // return the Bitmap of the image
                return bmp;
            }
            catch(Exception ex)
            {
                Logger.LogError("Error downloading thumb from {0} - {1}", URL, ex.Message);
                return null; // if for some reason we couldn't get to image, we return null
            }
        }

        public double GetCaseAspect(string emulatorTitle)
        {
            if (!Options.Instance.GetBoolOption("resizethumbs"))
                return 0;
            double aspect;
            if (!aspects.TryGetValue(emulatorTitle.ToLower(), out aspect))
            {
                Logger.LogDebug("No thumb aspect ratio info found for {0}, original ratio will be kept", emulatorTitle);
                aspect = 0; //keep original aspect
            }
            else
                Logger.LogDebug("Using thumb aspect ratio {1}", aspect);
            return aspect;
        }

        Dictionary<string, double> loadAspects()
        {
            Dictionary<string, double> aspects = new Dictionary<string, double>();
            Logger.LogDebug("Loading aspect ratios...");

            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(Config.GetFile(Config.Dir.Config, "myEmulatorsAspectRatios.xml"));
            }
            catch(Exception ex)
            {
                Logger.LogError("Error loading aspect ratios - {0}", ex.Message);
                return aspects;
            }
            XmlNodeList items = doc.GetElementsByTagName("item");
            for (int x = 0; x < items.Count; x++)
            {
                double aspect;
                if (double.TryParse(items[x].InnerText, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out aspect))
                {
                    aspects.Add(items[x].Attributes.GetNamedItem("name").Value.ToLower(), aspect);
                    //Logger.LogDebug("Setting {0} aspect ratio to {1}", items[x].Attributes.GetNamedItem("name").Value.ToLower(), aspect);
                }
                else if (items[x].InnerText != "")
                    Logger.LogDebug("Unable to parse aspect ratio for {0}", items[x].Attributes.GetNamedItem("name").Value);
            }

            return aspects;
        }

    }

}
